using System;
using System.Collections;
using System.Collections.Generic;


namespace LightCAD.Three
{
    public class PolarGridHelper : LineSegments
    {
        #region constructor
        public PolarGridHelper(double radius = 10, double sectors = 16, double rings = 8, double divisions = 64, int color1 = 0x444444, int color2 = 0x888888)
            : base(makeGeometry(radius, sectors, rings, divisions, new Color(color1), new Color(color2)), new LineBasicMaterial(new MaterialValues() { vertexColors = true, toneMapped = false }))
        {
            this.type = "PolarGridHelper";
        }
        private static BufferGeometry makeGeometry(double radius, double sectors, double rings, double divisions, Color color1, Color color2)
        {
            var vertices = new JsArr<double>();
            var colors = new JsArr<double>();
            // create the sectors
            if (sectors > 1)
            {
                for (int i = 0; i < sectors; i++)
                {
                    var v = (i / sectors) * (JMath.PI * 2);
                    var x = JMath.sin(v) * radius;
                    var z = JMath.cos(v) * radius;
                    vertices.push(0, 0, 0);
                    vertices.push(x, 0, z);
                    var color = (i & 1) == 1 ? color1 : color2;
                    colors.push(color.r, color.g, color.b);
                    colors.push(color.r, color.g, color.b);
                }
            }
            // create the rings
            for (int i = 0; i < rings; i++)
            {
                var color = (i & 1) == 1 ? color1 : color2;
                var r = radius - (radius / rings * i);
                for (int j = 0; j < divisions; j++)
                {
                    // first vertex
                    var v = (j / divisions) * (JMath.PI * 2);
                    var x = JMath.sin(v) * r;
                    var z = JMath.cos(v) * r;
                    vertices.push(x, 0, z);
                    colors.push(color.r, color.g, color.b);
                    // second vertex
                    v = ((j + 1) / divisions) * (JMath.PI * 2);
                    x = JMath.sin(v) * r;
                    z = JMath.cos(v) * r;
                    vertices.push(x, 0, z);
                    colors.push(color.r, color.g, color.b);
                }
            }
            var geometry = new BufferGeometry();
            geometry.setAttribute("position", new Float32BufferAttribute(vertices.ToArray(), 3));
            geometry.setAttribute("color", new Float32BufferAttribute(colors.ToArray(), 3));

            return geometry;
        }
        #endregion

        #region methods
        public void dispose()
        {
            this.geometry.dispose();
            this.material.dispose();
        }
        #endregion

    }
}
